package com.jcfk.eam.controller.mt;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.jcfk.common.business.log.annotation.RequestLogHeader;
import com.jcfk.common.core.utils.ExcelUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.ReqPageParam;
import com.jcfk.common.web.domain.RetPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.controller.parent.EamAssetInfoController;
import com.jcfk.eam.domain.dto.base.EamAssetTypeDTO;
import com.jcfk.eam.domain.dto.main.EamAssetInfoDTO;
import com.jcfk.eam.domain.excel.main.EamAssetInfoExcel;
import com.jcfk.eam.domain.excel.mt.MtAssetInfoExcel;
import com.jcfk.eam.domain.query.main.EamAssetInfoQuery;
import com.jcfk.eam.domain.uploadExcel.main.EamAssetInfoUploadExcel;
import com.jcfk.eam.domain.uploadExcel.mt.MtEamAssetInfoUploadExcel;
import com.jcfk.eam.enums.AssetKind;
import com.jcfk.eam.service.base.EamAssetTypeService;
import com.jcfk.eam.service.main.EamAssetInfoService;
import com.jcfk.eam.service.mt.MtAssetInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 量检具台账 服务接口
 *
 * @author libinghai
 * @email 35738025@gqq.com
 * @date 2024-07-28
 */
@Api(tags = {"量检具台账"})
@RestController
@RequestMapping("mtAssetInfo")
public class MtAssetInfoController {
    @Autowired
    private EamAssetInfoController assetInfoController;

    @Autowired
    private MtAssetInfoService mtAssetInfoService;

    /**
     * 分页列表
     */
    @ApiOperation("分页查询量检具台账")
    @PostMapping("/queryByPage")
    public RetPage<EamAssetInfoDTO> queryByPage(@RequestBody ReqPageParam<EamAssetInfoQuery> requestParam) {
        requestParam.getData().setAssetKind(AssetKind.MEASURING_TOOL.getValue());
        RetPage<EamAssetInfoDTO> pageResult = assetInfoController.queryByPage(requestParam);
        return pageResult;
    }


    /**
     * 量检具台账
     * 根据id 查询详情
     */
    @ApiOperation("查询量检具台账")
    @GetMapping("/get/{id}")
    public RetResult<EamAssetInfoDTO> get(@PathVariable("id") String id) {
        RetResult<EamAssetInfoDTO> itemResult = assetInfoController.get(id);
        return itemResult;
    }

    /**
     * 添加/更新管理量检具台账
     */
    @ApiOperation("保存量检具台账")
    @PostMapping("/save")
    @RequestLogHeader(modular = "量检具台账管理", businessType = "保存")
    public RetResult<?> save(@RequestBody @Valid EamAssetInfoDTO eamAssetInfo) {
        eamAssetInfo.setAssetKind(AssetKind.MEASURING_TOOL.getValue());
        eamAssetInfo.setAssetQuantity(1);

        // 数据校验
        RetResult ret = mtAssetInfoService.isValid(eamAssetInfo);
        if (!ret.getCode().equals(RetResult.SUCCESS)) {
            return ret;
        }

        RetResult<?> result = assetInfoController.save(eamAssetInfo);
        return result;
    }

    /**
     * 批量删除量检具台账
     */
    @ApiOperation("批量删除量检具台账")
    @PostMapping("/delete")
    @RequestLogHeader(modular = "量检具台账管理", businessType = "批量删除")
    public RetResult<?> delete(@RequestBody EamAssetInfoDTO eamAssetInfo) {
        RetResult<?> result = assetInfoController.delete(eamAssetInfo);
        return result;
    }

    @PostMapping("export")
    @ApiOperation("导出")
    public void export(@RequestBody EamAssetInfoQuery requestParam, HttpServletResponse response) throws Exception {
        requestParam.setAssetKind(AssetKind.MEASURING_TOOL.getValue());
        assetInfoController.export(requestParam, response, MtAssetInfoExcel.class);
    }

    /**
     * 导入资产台账
     */
    @PostMapping("upload")
    public RetResult<?> upload(MultipartFile file) throws IOException {
        // 读取excel
        List<MtEamAssetInfoUploadExcel> items = EasyExcel.read(file.getInputStream(), MtEamAssetInfoUploadExcel.class,null)
            .autoCloseStream(true)
            .sheet(0)
            .headRowNumber(3)
            .autoTrim(true)
            .doReadSync();
        return RetResult.ok(mtAssetInfoService.upload(items));
//        if (!upload){
//            File convFile = File.createTempFile("temp", file.getOriginalFilename());
//            ExcelWriter writer = EasyExcel.write(convFile.getAbsolutePath(), MtEamAssetInfoUploadExcel.class).build();
//            // 写入数据到Excel
//            WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();
//            writer.write(items, writeSheet);
//            // 完成导出操作并关闭writer
//            writer.finish();
//            return RetResult.ok(convFile.getAbsolutePath());
//        }
//        return RetResult.ok();
    }

    /**
     * 下载异常文件
     */
    @PostMapping("errorFile")
    @ApiOperation("下载异常文件")
    public void errorFile(String filePath, HttpServletResponse response) throws Exception {
        File file = new File(filePath);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8") + ".xls");
        ServletOutputStream out = response.getOutputStream();
        // 将文件内容写入响应输出流
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        }
        out.close();
        FileUtil.del(file);
    }

//
//    /**
//     * 下载模板
//     */
//    @PostMapping("exportTemp")
//    @ApiOperation("下载模板")
//    public void exportTemp(HttpServletResponse response) throws Exception {
//        List<EamAssetInfoUploadExcel> list = new ArrayList<>();
//        list.add(new EamAssetInfoUploadExcel());
//        ExcelUtils.exportExcelToTarget(response, null, list, EamAssetInfoUploadExcel.class);
//    }


    /**
     * 删除量检具台账
     */
    @ApiOperation("删除量检具台账")
    @PostMapping("/deleteItem/{id}")
    @RequestLogHeader(modular = "量检具台账管理", businessType = "删除")
    public RetResult<?> deleteItem(@PathVariable("id") String id) {
        RetResult<?> result = assetInfoController.deleteItem(id);
        return result;
    }
}
